/**
 * Sangame.com Inc.
 * Copyright (c) 2006-2011 All Rights Reserved.
 */
package com.nmp.service.taobao;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import weibo4j.org.json.JSONObject;

import com.nmp.config.CommonConfig;
import com.nmp.service.base.result.DefaultResult;
import com.nmp.service.base.result.Result;
import com.nmp.service.base.result.ResultCode;
import com.taobao.api.Constants;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.WebUtils;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.response.UserGetResponse;

/**
 * 淘宝用户信息服务接口
 * @author defier.lai
 * 2011-11-27 下午02:16:06
 * @version 1.0
 */
@Service
public class TaobaoUserService {
	
	private final static Logger LOG	= LoggerFactory.getLogger(TaobaoUserService.class);
	
	@Resource
	private CommonConfig commonConfig;

	public Result getAccountAuthorizeUrl() {
		Result result = new DefaultResult(true);
		try {
			String authorizeUrl = Constants.PRODUCT_AUTHORIZE_URL;
			String appKey = Constants.PRODUCT_APP_KEY;
			if(commonConfig.isDebugMode()) {
				authorizeUrl = Constants.SANDBOX_AUTHORIZE_URL;
				appKey = Constants.SANDBOX_APP_KEY;
			}
            authorizeUrl = authorizeUrl + "?response_type=code&client_id="+appKey+"&state=&redirect_uri="+commonConfig.getTaobaoCallback() ;
            result.setDefaultModel(authorizeUrl);
            
		} catch (Exception e) {
			LOG.error("authorize url is error!", e);
			result.setResultCode(new ResultCode(ResultCode.FAILURE));
		}
		return result;
	}
	
	public Result bindTaobaoToken(String code) {
		Result result = new DefaultResult(true);
		try {
			String tokenUrl = Constants.PRODUCT_TOKEN_URL;
			String appKey = Constants.PRODUCT_APP_KEY;
			String appSecret = Constants.PRODUCT_APP_SECRET;
			String apiUrl = Constants.PRODUCT_API_URL;
			
			if(commonConfig.isDebugMode()) {
				tokenUrl = Constants.SANDBOX_TOKEN_URL;
				appKey = Constants.SANDBOX_APP_KEY;
				appSecret = Constants.SANDBOX_APP_SECRET;
				apiUrl = Constants.SANDBOX_API_URL;
			}
            Map<String,String> props = new HashMap<String,String>();
            props.put("grant_type", "authorization_code");
            props.put("code", code);
            props.put("client_id", appKey);
            props.put("client_secret", appSecret);
            props.put("redirect_uri", commonConfig.getTaobaoCallback());
            String tokenString = WebUtils.doPost(tokenUrl, props, 30000, 30000);
            String access_token = "";
            JSONObject jb = new JSONObject(tokenString); //解析获取token
            //判断是否获取到token，若获取失败，可以根据返回的错误描述排查
            if(!jb.has("error")) {
                access_token = jb.getString("access_token");
                //获取当前登录用户nick等数据，access_token就相当于sessionkey，后续调用其他接口可以直接使用
                TaobaoClient client = new DefaultTaobaoClient(apiUrl, appKey, appSecret);
                UserGetRequest req = new UserGetRequest();
                req.setFields("user_id, uid, nick");
                UserGetResponse resp = client.execute(req , access_token);
                if (resp.isSuccess()) {
                    //获取nick
                	String nick = resp.getUser().getNick();
                }
            } else {
            	LOG.error("bind taobao token is error!", jb.toString());
            	result.setResultCode(new ResultCode(ResultCode.FAILURE, jb.toString()));
            }
		} catch (Exception e) {
			LOG.error("bind taobao token is exception!", e);
			result.setResultCode(new ResultCode(ResultCode.FAILURE));
		}
		return result;
	}


}
